package com.imedway.ihe.dd.util;

import org.apache.commons.io.IOUtils;

import javax.activation.DataHandler;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author bovane bovane.ch@gmial.com
 * @create 2024/7/29
 */
public abstract class ContentUtils {

    private ContentUtils() {
        throw new UnsupportedOperationException("Cannot be instantiated");
    }

    /**
     * Calculates the size of the given content stream.
     * @param dataHandler
     *          the data handler to access the content.
     * @return the size in bytes.
     */
    public static int size(DataHandler dataHandler) throws IOException {
        byte[] content = getContent(dataHandler);
        int size = content.length;
        return size;
    }

    /**
     * Calculates the SHA-1 of the given content stream.
     * @param dataHandler
     *          the data handler to access the content.
     * @return the SHA-1.
     */
    public static String sha1(DataHandler dataHandler) throws IOException, NoSuchAlgorithmException {
        byte[] content = getContent(dataHandler);
        return calcSha1(content);
    }

    private static String  calcSha1(byte[] content) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-1");
        StringBuilder builder = new StringBuilder();
        byte[] temp = digest.digest(content);
        for (byte it : temp) {
            String hexString = Integer.toHexString((int)it & 0xff);
            builder.append(hexString.length() == 2 ? hexString : '0' + hexString);
        }
        return builder.toString();
    }

    /**
     * Retrieves the byte array from a datahandler.
     * @param dataHandler
     *          the data handler to access the content.
     * @return the content as a byte[].
     */
    public static byte[] getContent(DataHandler dataHandler) throws IOException {
        InputStream inputStream = dataHandler.getInputStream();
        try {
            return IOUtils.toByteArray(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            inputStream.close();
        }
    }
}
